package com.rm.zeyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rm.zeyou.entity.CityVote;
import com.rm.zeyou.mapper.CityVoteMapper;
import com.rm.zeyou.response.ApiRestResponse;
import com.rm.zeyou.service.CityVoteService;
import com.rm.zeyou.util.address.AddressUtil;
import com.rm.zeyou.util.address.WSSsdrAddress;
import com.rm.zeyou.util.check.CheckEmptyUtil;
import com.rm.zeyou.util.gaode.GaoDeUtil;
import com.rm.zeyou.vo.request.AddCityVoteVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 城市投票表 服务实现类
 * </p>
 *
 * @author YanYang
 * @since 2025-03-14 17:20:22
 */
@Service
public class CityVoteServiceImpl extends ServiceImpl<CityVoteMapper, CityVote> implements CityVoteService {
    @Resource
    private CityVoteMapper cityVoteMapper;
    @Resource
    private GaoDeUtil gaoDeUtil;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Integer> addCityVote(Long userId, AddCityVoteVo addVo) {
        String address = gaoDeUtil.ReGeoCode(addVo.getLongitude() + "," + addVo.getLatitude());
        WSSsdrAddress wsSsdrAddress = AddressUtil.addressFormat(address);
        CityVote cityVote = cityVoteMapper.selectOneCity(!CheckEmptyUtil.isEmpty(wsSsdrAddress.getCity()) ? wsSsdrAddress.getCity() : wsSsdrAddress.getProvince());
        Integer result;
        if (!CheckEmptyUtil.isEmpty(cityVote)){
            result =  cityVoteMapper.addCount(cityVote.getId());
        }else {
            CityVote insertCityVote = new CityVote();
            cityVote.setUserId(userId);
            cityVote.setCityName(!CheckEmptyUtil.isEmpty(wsSsdrAddress.getCity()) ? wsSsdrAddress.getCity() : wsSsdrAddress.getProvince());
            result = cityVoteMapper.insert(insertCityVote);
        }


        return ApiRestResponse.success(result);
    }
}
